/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package laba8;

  import java.util.Iterator;
  import java.util.Set;
  
  import org.objectweb.asm.ClassAdapter;
  import org.objectweb.asm.ClassVisitor;
  import org.objectweb.asm.MethodAdapter;
  import org.objectweb.asm.MethodVisitor;
  import org.objectweb.asm.Opcodes;
  
  public class ClassRenamer extends ClassAdapter implements Opcodes {
  
      private Set oldNames;
      private final String newName;
  
      public ClassRenamer(ClassVisitor cv, Set oldNames, String newName) {
          super(cv);
          this.oldNames = oldNames;
          this.newName = newName;
      }
  
      public void visit(int version, int access, String name, String signature,
              String superName, String[] interfaces) {
          oldNames.add(name);
          cv
                  .visit(version, ACC_PUBLIC, newName, signature, superName,
                          interfaces);
      }
  
      public MethodVisitor visitMethod(int access, String name, String desc,
              String signature, String[] exceptions) {
          MethodVisitor mv = cv.visitMethod(access, name, fix(desc),
                  fix(signature), exceptions);
          if (mv != null && (access & ACC_ABSTRACT) == 0) {
              mv = new MethodRenamer(mv);
          }
          return mv;
      }
  
      class MethodRenamer extends MethodAdapter {
  
          public MethodRenamer(final MethodVisitor mv) {
              super(mv);
          }
  
          public void visitTypeInsn(int i, String s) {
              if (oldNames.contains(s)) {
                  s = newName;
              }
              mv.visitTypeInsn(i, s);
          }
  
          public void visitFieldInsn(int opcode, String owner, String name,
                  String desc) {
              if (oldNames.contains(owner)) {
                  mv.visitFieldInsn(opcode, newName, name, fix(desc));
              } else {
                  mv.visitFieldInsn(opcode, owner, name, fix(desc));
              }
          }
  
          public void visitMethodInsn(int opcode, String owner, String name,
                  String desc) {
              if (oldNames.contains(owner)) {
                  mv.visitMethodInsn(opcode, newName, name, fix(desc));
              } else {
                  mv.visitMethodInsn(opcode, owner, name, fix(desc));
              }
          }
      }
  
      private String fix(String s) {
          if (s != null) {
              Iterator it = oldNames.iterator();
              String name;
              while (it.hasNext()) {
                  name = (String) it.next();
                  if (s.indexOf(name) != -1) {
                      s = s.replaceAll(name, newName);
                  }
              }
          }
          return s;
      }
  
  }

